package com.xzxy.xmlg_backend.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xzxy.xmlg_backend.entity.Announcements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 公告初始化服务
 * 系统启动时恢复定时任务
 * @author 周毅盛
 * @since 2025-06-16
 */
@Service
public class AnnouncementInitService implements ApplicationRunner {

    @Autowired
    private IAnnouncementsService announcementsService;

    @Autowired
    private AnnouncementScheduleService scheduleService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 系统启动时恢复定时任务
        restoreScheduledTasks();
    }

    /**
     * 恢复定时任务
     * 查找所有状态为"暂存"且发布时间在未来的公告，重新创建定时任务
     */
    private void restoreScheduledTasks() {
        try {
            System.out.println("开始恢复定时任务，当前时间: " + LocalDateTime.now());
            
            LambdaQueryWrapper<Announcements> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Announcements::getPublishStatus, "暂存")
                   .gt(Announcements::getPublishTime, LocalDateTime.now());
            
            List<Announcements> pendingAnnouncements = announcementsService.list(wrapper);
            System.out.println("找到 " + pendingAnnouncements.size() + " 个待发布的公告");
            
            for (Announcements announcement : pendingAnnouncements) {
                System.out.println("恢复定时任务 - 公告ID: " + announcement.getId() + 
                    ", 标题: " + announcement.getTitle() + 
                    ", 发布时间: " + announcement.getPublishTime());
                    
                scheduleService.scheduleAnnouncement(
                    announcement.getId(), 
                    announcement.getPublishTime()
                );
            }
            
            if (!pendingAnnouncements.isEmpty()) {
                System.out.println("已恢复 " + pendingAnnouncements.size() + " 个公告的定时发布任务");
            } else {
                System.out.println("没有需要恢复的定时任务");
            }
        } catch (Exception e) {
            System.err.println("恢复定时任务失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}